from flask import Blueprint, render_template, request, current_app, jsonify, url_for
from flask_login import login_required, current_user
from fileshare.extensions import csrf, db
from fileshare.models import FileInfo
import traceback
import os
import base64

filetype_bp = Blueprint('filetype', __name__)


@csrf.exempt
@filetype_bp.route('/image', methods=['GET', 'POST'])
@login_required
def image_page():
    if request.method == 'POST':
        response = {'status': False}
        try:
            sqlResult = FileInfo.query.filter_by(
                username=current_user.username, filetype='image').all()
            result = []
            for i in sqlResult:
                if os.path.exists(i.filepath):
                    result.append(i.to_json())
            response['data'] = result
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(traceback.format_exc())
            response['code'] = 4000
            response['msg'] = str(e)
            return jsonify(response)
        response['code'] = 0
        response['msg'] = 'success'
        response['status'] = True
        return jsonify(response)
    return render_template('file/filetype.html', url=url_for('filetype.image_page'),
                           sep=base64.b64encode(os.path.sep.encode()).decode())


@csrf.exempt
@filetype_bp.route('/document', methods=['GET', 'POST'])
@login_required
def document_page():
    if request.method == 'POST':
        response = {'status': False}
        try:
            sqlResult = FileInfo.query.filter_by(
                username=current_user.username, filetype='document').all()
            result = []
            for i in sqlResult:
                if os.path.exists(i.filepath):
                    result.append(i.to_json())
            response['data'] = result
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(traceback.format_exc())
            response['code'] = 4000
            response['msg'] = str(e)
            return jsonify(response)
        response['code'] = 0
        response['msg'] = 'success'
        response['status'] = True
        return jsonify(response)
    return render_template('file/filetype.html', url=url_for('filetype.document_page'),
                           sep=base64.b64encode(os.path.sep.encode()).decode())


@csrf.exempt
@filetype_bp.route('/video', methods=['GET', 'POST'])
@login_required
def video_page():
    if request.method == 'POST':
        response = {'status': False}
        try:
            sqlResult = FileInfo.query.filter_by(
                username=current_user.username, filetype='video').all()
            result = []
            for i in sqlResult:
                if os.path.exists(i.filepath):
                    result.append(i.to_json())
            response['data'] = result
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(traceback.format_exc())
            response['code'] = 4000
            response['msg'] = str(e)
            return jsonify(response)
        response['code'] = 0
        response['msg'] = 'success'
        response['status'] = True
        return jsonify(response)
    return render_template('file/filetype.html', url=url_for('filetype.video_page'),
                           sep=base64.b64encode(os.path.sep.encode()).decode())


@csrf.exempt
@filetype_bp.route('/torrent', methods=['GET', 'POST'])
@login_required
def torrent_page():
    if request.method == 'POST':
        response = {'status': False}
        try:
            sqlResult = FileInfo.query.filter_by(
                username=current_user.username, filetype='torrent').all()
            result = []
            for i in sqlResult:
                if os.path.exists(i.filepath):
                    result.append(i.to_json())
            response['data'] = result
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(traceback.format_exc())
            response['code'] = 4000
            response['msg'] = str(e)
            return jsonify(response)
        response['code'] = 0
        response['msg'] = 'success'
        response['status'] = True
        return jsonify(response)
    return render_template('file/filetype.html', url=url_for('filetype.torrent_page'),
                           sep=base64.b64encode(os.path.sep.encode()).decode())


@csrf.exempt
@filetype_bp.route('/radio', methods=['GET', 'POST'])
@login_required
def radio_page():
    if request.method == 'POST':
        response = {'status': False}
        try:
            sqlResult = FileInfo.query.filter_by(
                username=current_user.username, filetype='radio').all()
            result = []
            for i in sqlResult:
                if os.path.exists(i.filepath):
                    result.append(i.to_json())
            response['data'] = result
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(traceback.format_exc())
            response['code'] = 4000
            response['msg'] = str(e)
            return jsonify(response)
        response['code'] = 0
        response['msg'] = 'success'
        response['status'] = True
        return jsonify(response)
    return render_template('file/filetype.html', url=url_for('filetype.radio_page'),
                           sep=base64.b64encode(os.path.sep.encode()).decode())


@csrf.exempt
@filetype_bp.route('/other', methods=['GET', 'POST'])
@login_required
def other_page():
    if request.method == 'POST':
        response = {'status': False}
        try:
            sqlResult = FileInfo.query.filter_by(
                username=current_user.username, filetype='other').all()
            result = []
            for i in sqlResult:
                if os.path.exists(i.filepath):
                    result.append(i.to_json())
            response['data'] = result
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(traceback.format_exc())
            response['code'] = 4000
            response['msg'] = str(e)
            return jsonify(response)
        response['code'] = 0
        response['msg'] = 'success'
        response['status'] = True
        return jsonify(response)
    return render_template('file/filetype.html', url=url_for('filetype.other_page'),
                           sep=base64.b64encode(os.path.sep.encode()).decode())
